<?php
declare (strict_types=1);

// +----------------------------------------------------------------------
// | SCApi
// +----------------------------------------------------------------------
// | 版权所有 2021~2022 贾二小 [ http://www.ipsoul.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://www.ipsoul.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// | 免费声明 ( http://doc.ipsoul.com/disclaimer )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/jiaerxiao/scapi
// | github 代码仓库：https://github.com/jiaerxiao/scapi
// +----------------------------------------------------------------------

namespace app\system\service;

use app\common\service\BaseService;
use think\App;

class RoleService extends BaseService
{
    /**
     * 初始化
     * @param App $app
     */
    public function __construct(App $app)
    {
        parent::__construct($app, '角色管理', 'role');
    }

    /**
     * 表格数据
     * @author 贾二小
     * @since 2021/11/20
     */
    public function tableList(string $keyword): array
    {
        $map = [];
        if (!empty($keyword)) {
            $map[] = ['label|alias', 'like', '%' . trim($keyword) . '%'];
        }
        return $this->list($map)->toArray();
    }

    /**
     * 树结构
     * @author 贾二小
     * @since 2021/11/20
     */
    public function tree(): array
    {
        $data = array_map(function ($item) {
            $item['parentIds'] = json_decode($item['parentIds'], true);
            return $item;
        }, $this->list()->toArray());
        return get_tree($data, 0);
    }

    /**
     * 保存
     * @throws \think\db\exception\DbException
     * @since 2021/12/5
     * @author 贾二小
     */
    public function saving(array $paramData)
    {
        if (isset($paramData['parentId']) && !empty($paramData['parentId'])) {
            $parentData = $this->infoById($paramData['parentId']);
            $parentIds = json_decode($parentData['parentIds'], true);
            array_push($parentIds, $paramData['parentId']);
            $paramData['parentIds'] = json_encode($parentIds);
        } else {
            $paramData['parentId'] = 0;
            $paramData['parentIds'] = '[0]';
        }
        if (isset($paramData['id']) && $paramData['id'] > 0) {
            return $this->updateById($paramData['id'], $paramData);
        } else {
            return $this->insertGetId($paramData);
        }
    }
}